package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.Company;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyEmployeeService;
import com.xuanzheng.company.service.CompanyService;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.CompanyEmployeeServiceImpl;
import com.xuanzheng.company.service.impl.CompanyServiceImpl;
import com.xuanzheng.company.service.impl.UserServiceImpl;
import com.xuanzheng.company.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/deleteCompany")
public class DeleteCompanyServlet extends HttpServlet {
    private final CompanyService companyService = new CompanyServiceImpl();
    private final CompanyEmployeeService companyEmployeeService = new CompanyEmployeeServiceImpl();
    private final UserService userService = new UserServiceImpl();
    private final Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        // 获取当前登录用户
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            out.print(gson.toJson(result));
            return;
        }

        User currentUser = (User) session.getAttribute("user");
        
        // 验证用户是否是公司负责人
        if (currentUser.getRole() != 1) {
            result.put("success", false);
            result.put("message", "只有公司负责人可以注销公司");
            out.print(gson.toJson(result));
            return;
        }

        // 获取公司信息
        Company company = companyService.getCompanyByManagerId(currentUser.getId());
        if (company == null) {
            result.put("success", false);
            result.put("message", "未找到公司信息");
            out.print(gson.toJson(result));
            return;
        }
        
        String companyId = company.getId();
        
        // 执行公司注销操作
        boolean success = deleteCompany(companyId, currentUser.getId());

        if (success) {
            result.put("success", true);
            result.put("message", "公司已成功注销");
            
            // 更新会话中的用户信息
            currentUser.setCompanyId(null);
            currentUser.setEmployeeNumber(null);
            session.setAttribute("user", currentUser);
        } else {
            result.put("success", false);
            result.put("message", "公司注销失败，请稍后重试");
        }

        out.print(gson.toJson(result));
    }
    
    private boolean deleteCompany(String companyId, String managerId) {
        Connection conn = null;
        boolean success = false;
        
        try {
            System.out.println("开始注销公司，公司ID=" + companyId + ", 负责人ID=" + managerId);
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false);
            
            // 1. 获取除了负责人外的所有员工ID
            List<String> employeeIds = getEmployeeIds(conn, companyId, managerId);
            System.out.println("找到" + employeeIds.size() + "名员工需要解除关联");
            
            // 2. 删除员工与公司的关联
            if (!employeeIds.isEmpty()) {
                // 清除所有员工的公司ID和员工编号
                updateUserCompanyInfo(conn, employeeIds);
                System.out.println("已清除员工的公司ID和员工编号");
                
                // 删除所有员工与公司的关联记录
                deleteCompanyEmployees(conn, companyId, managerId);
                System.out.println("已删除员工与公司的关联记录");
            }
            
            // 3. 删除公司相关的其他数据
            deleteCompanyAnnouncements(conn, companyId);
            deleteCompanyAttendanceRecords(conn, companyId);
            deleteCompanyAttendanceSettings(conn, companyId);
            deleteCompanyTasks(conn, companyId);
            deleteCompanyEmployeePerformance(conn, companyId);
            deleteCompanyApplications(conn, companyId);
            System.out.println("已删除公司相关的其他数据");
            
            // 4. 删除公司记录
            deleteCompanyRecord(conn, companyId);
            System.out.println("已删除公司记录");
            
            // 5. 删除负责人账号
            deleteManagerAccount(conn, managerId);
            System.out.println("已删除负责人账号");
            
            // 提交事务
            conn.commit();
            success = true;
            System.out.println("公司注销成功完成");
            
        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println("公司注销失败，错误: " + e.getMessage());
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        } finally {
            if (conn != null) {
                try {
                    conn.setAutoCommit(true);
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        
        return success;
    }
    
    private List<String> getEmployeeIds(Connection conn, String companyId, String managerId) throws SQLException {
        List<String> employeeIds = new ArrayList<>();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            String sql = "SELECT user_id FROM company_employee WHERE company_id = ? AND user_id != ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, companyId);
            pstmt.setString(2, managerId);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                employeeIds.add(rs.getString("user_id"));
            }
        } finally {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
        }
        
        return employeeIds;
    }
    
    private void updateUserCompanyInfo(Connection conn, List<String> userIds) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            String sql = "UPDATE user SET company_id = NULL, employee_number = NULL WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            
            for (String userId : userIds) {
                pstmt.setString(1, userId);
                pstmt.executeUpdate();
            }
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }
    
    private void deleteCompanyEmployees(Connection conn, String companyId, String managerId) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            // 删除所有员工与公司的关联记录，包括负责人的记录
            String sql = "DELETE FROM company_employee WHERE company_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, companyId);
            pstmt.executeUpdate();
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }
    
    private void deleteCompanyAnnouncements(Connection conn, String companyId) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            String sql = "DELETE FROM company_announcement WHERE company_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, companyId);
            pstmt.executeUpdate();
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }
    
    private void deleteCompanyAttendanceRecords(Connection conn, String companyId) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            String sql = "DELETE FROM attendance_record WHERE company_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, companyId);
            pstmt.executeUpdate();
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }
    
    private void deleteCompanyAttendanceSettings(Connection conn, String companyId) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            String sql = "DELETE FROM attendance_setting WHERE company_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, companyId);
            pstmt.executeUpdate();
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }
    
    private void deleteCompanyTasks(Connection conn, String companyId) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            String sql = "DELETE FROM task WHERE company_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, companyId);
            pstmt.executeUpdate();
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }
    
    private void deleteCompanyEmployeePerformance(Connection conn, String companyId) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            String sql = "DELETE FROM employee_performance WHERE company_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, companyId);
            pstmt.executeUpdate();
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }
    
    private void deleteCompanyApplications(Connection conn, String companyId) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            String sql = "DELETE FROM company_employee WHERE company_id = ? AND status IN (0, 2, 3)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, companyId);
            pstmt.executeUpdate();
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }
    
    private void updateCompanyStatus(Connection conn, String companyId) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            String sql = "UPDATE company SET status = 0 WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, companyId);
            pstmt.executeUpdate();
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }

    // 删除公司记录
    private void deleteCompanyRecord(Connection conn, String companyId) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            String sql = "DELETE FROM company WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, companyId);
            pstmt.executeUpdate();
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }
    
    // 删除负责人账号
    private void deleteManagerAccount(Connection conn, String managerId) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            String sql = "DELETE FROM user WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, managerId);
            pstmt.executeUpdate();
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }
} 